<script setup>
import { ref, onMounted } from 'vue'

const message = ref('Hello Serial Port')
const ports = ref([])
const connected = ref(false)
const selectedPort = ref('COM1')
const baudRate = ref(115200)
const sendDataText = ref('')
const receivedData = ref('')
const sendDataType = ref('string')

// 检查 serialAPI 是否可用
const checkSerialAPI = () => {
  return typeof window !== 'undefined' && window.serialAPI
}

// 列出可用的串口
const listPorts = async () => {
  try {
    if (!checkSerialAPI()) {
      throw new Error('Serial API not available')
    }

    console.log('Requesting port list...');
    ports.value = await window.serialAPI.listPorts()
    console.log('Available ports:', ports.value)
    message.value = `Found ${ports.value.length} ports`
  } catch (error) {
    console.error('Error listing ports:', error)
    message.value = `Error listing ports: ${error.message}`
  }
}

// 连接到串口
const connect = async () => {
  try {
    if (!checkSerialAPI()) {
      throw new Error('Serial API not available')
    }

    message.value = `Connecting to ${selectedPort.value}...`
    console.log(`Connecting to ${selectedPort.value} at ${baudRate.value} baud`);

    await window.serialAPI.connect(selectedPort.value, { baudRate: parseInt(baudRate.value) })
    connected.value = true
    message.value = `Connected to ${selectedPort.value}`

    // 设置接收数据的回调
    window.serialAPI.onReceiveData((data) => {
      console.log('Received data:', data);
      receivedData.value += data
    })

    window.serialAPI.onReceiveError((error) => {
      console.error('Receive error:', error);
      message.value = `Receive error: ${error}`
    })
  } catch (error) {
    console.error('Error connecting to port:', error)
    message.value = `Connection failed: ${error.message}`
  }
}

// 主动创建一个115200波特率的串口连接
const connect115200 = async () => {
  if (ports.value.length > 0) {
    selectedPort.value = ports.value[0].path
    baudRate.value = 115200
    await connect()
  } else {
    message.value = 'No available ports found'
  }
}

// 断开连接
const disconnect = async () => {
  try {
    if (!checkSerialAPI()) {
      throw new Error('Serial API not available')
    }

    message.value = 'Disconnecting...'
    await window.serialAPI.disconnect()
    connected.value = false
    message.value = 'Disconnected'
    receivedData.value = '' // 断开连接时清空接收数据
  } catch (error) {
    console.error('Error disconnecting:', error)
    message.value = `Disconnection failed: ${error.message}`
  }
}

// 发送数据
const sendData = async () => {
  try {
    if (!checkSerialAPI()) {
      throw new Error('Serial API not available')
    }

    if (!sendDataText.value) {
      message.value = 'Please enter data to send'
      return
    }

    message.value = `Sending: ${sendDataText.value}`
    await window.serialAPI.sendData(sendDataText.value)
    message.value = `Sent: ${sendDataText.value}`
  } catch (error) {
    console.error('Error sending data:', error)
    message.value = `Send failed: ${error.message}`
  }
}

// 发送不同类型的数据（模拟你提到的几种方式）
const sendSpecialData = async (type) => {
  try {
    if (!checkSerialAPI()) {
      throw new Error('Serial API not available')
    }

    let dataToSend = ''
    switch (type) {
      case 'hello':
        dataToSend = 'Hello world!\n'
        break
      case 'buffer':
        // 在前端我们只能发送字符串，转换会在主进程中处理
        dataToSend = 'Hey!\n'
        break
      case 'uint8array':
        // 发送十六进制表示的字节数组
        dataToSend = String.fromCharCode(0x48, 0x69, 0x21, 0x0A) // "Hi!\n"
        break
      default:
        message.value = 'Unknown data type'
        return
    }

    message.value = `Sending special data (${type})...`
    await window.serialAPI.sendData(dataToSend+'\n')
    message.value = `Sent special data (${type}): ${JSON.stringify(dataToSend)}`
  } catch (error) {
    console.error('Error sending special data:', error)
    message.value = `Send failed: ${error.message}`
  }
}

// 清空接收数据
const clearReceivedData = () => {
  receivedData.value = ''
}

// 组件挂载后列出串口
onMounted(() => {
  if (checkSerialAPI()) {
    listPorts()
  } else {
    message.value = 'Serial API not available. Running in browser mode.'
    console.log('Running in browser mode - serial API not available')
  }
})

const serialConfig = {
  path: 'COM3',
  baudRate: 115200,
};
</script>

<template>
  <div class="container">
    <h1>1133</h1>
    <h1>李俊泽</h1>
    <p>{{ message }}</p>

    <div v-if="checkSerialAPI()">
      <h2>Serial Port Connection</h2>
      <div>
        <label for="port-select">Select Port:</label>
        <select id="port-select" v-model="selectedPort" :disabled="connected">
          <option value="">Select a port</option>
          <option v-for="port in ports" :key="port.path" :value="port.path">
            {{ port.path }} - {{ port.manufacturer || 'Unknown' }}
          </option>
        </select>
        <button @click="listPorts">Refresh Ports</button>
      </div>

      <div>
        <label for="baud-rate">Baud Rate:</label>
        <input id="baud-rate" type="number" v-model="baudRate" :disabled="connected" />
      </div>

      <div>
        <button v-if="!connected" @click="connect" :disabled="!selectedPort">Connect</button>
        <button v-else @click="disconnect">Disconnect</button>
        <button @click="connect115200">Connect 115200</button>
      </div>

      <!-- 发送数据区域 -->
      <div v-if="connected">
        <h3>Send Data</h3>
        <div>
          <input v-model="sendDataText" placeholder="Enter data to send" />
          <button @click="sendData">Send</button>
        </div>

        <!-- 特殊数据发送按钮 -->
        <div>
          <h4>Send Special Data</h4>
          <button @click="sendSpecialData('hello')">Send "Hello world!"</button>
          <button @click="sendSpecialData('buffer')">Send Buffer Data</button>
          <button @click="sendSpecialData('uint8array')">Send Uint8Array Data</button>
        </div>
      </div>

      <!-- 接收数据显示区域 -->
      <div v-if="connected">
        <h3>Received Data</h3>
        <div class="received-data-container">
          <div class="received-data">{{ receivedData }}</div>
          <button @click="clearReceivedData">Clear</button>
        </div>
      </div>
    </div>

    <div v-else>
      <p>Serial Port functionality is only available in the Electron application.</p>
    </div>
  </div>
</template>

<style scoped>
.container {
  text-align: center;
  padding: 20px;
}

div {
  margin: 10px 0;
}

select, input, button {
  padding: 5px;
  margin: 5px;
}

.received-data-container {
  text-align: left;
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px 0;
  max-height: 200px;
  overflow-y: auto;
}

.received-data {
  white-space: pre-wrap;
  font-family: monospace;
  min-height: 50px;
}
</style>
